package com.dyz.resource;

import cn.hutool.core.io.resource.ClassPathResource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;
import org.springframework.security.oauth2.provider.token.store.JwtTokenStore;
import org.springframework.util.FileCopyUtils;

import java.io.IOException;

@Configuration
@EnableResourceServer
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class ResourceServerConfig extends ResourceServerConfigurerAdapter {
    /**
     * 拦截与放行
     * @param http
     * @throws Exception
     */
    @Override
    public void configure(HttpSecurity http) throws Exception {
        http.csrf().disable()
                .sessionManagement().disable()
                .authorizeRequests()
                .antMatchers(
                        "/login",
                        "/swagger-resources/**",
                        "/webjars/**",
                        "/doc.html",
                        "/swagger-ui.html/**",
                        "/webjars/**",
                        "/v2/api-docs/**"
                ).permitAll()
                .anyRequest().authenticated()
                .and().headers().cacheControl();

    }

    /**
     * 设置公钥
     * @param resources
     * @throws Exception
     */
    @Override
    public void configure(ResourceServerSecurityConfigurer resources) throws Exception {
      resources.tokenStore(jwtTokenStore());
    }

    private TokenStore jwtTokenStore() {
        return new JwtTokenStore(jwtAccessTokenConverter());
    }
    @Bean //放在spring容器中
    public JwtAccessTokenConverter jwtAccessTokenConverter() {
        //产生一个token需要密钥对，验证需要公钥
        JwtAccessTokenConverter jwtAccessTokenConverter = new JwtAccessTokenConverter();
        String s = null;
        try {
            ClassPathResource resource = new ClassPathResource("coinexchange.txt");
            //将resource中的内容读取出来，并设置到jwtAccessTokenConverter中
            byte[] bytes = FileCopyUtils.copyToByteArray(resource.getStream());
            s = new String(bytes, "UTF-8");
        } catch (IOException e) {
            e.printStackTrace();
        }
        jwtAccessTokenConverter.setVerifierKey(s);
        return jwtAccessTokenConverter;
    }
}
